package ucap.com.lesanapp.base.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Vibrator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.activitys.NewsDetailedActivity;
import ucap.com.lesanapp.base.BasePager;
import ucap.com.lesanapp.bean.DateBean;
import ucap.com.lesanapp.global.Constants;
import ucap.com.lesanapp.global.SettingsModelState;
import ucap.com.lesanapp.utils.NetworkStateUtils;
import ucap.com.lesanapp.utils.PrefUtils;
import ucap.com.lesanapp.view.WebViewDialog;


/**
 * Created by Administrator on 2016/7/27.
 */
public class TourBase extends BasePager {
    @Bind(R.id.ll_tour_loading)
    LinearLayout llLoading;
    @Bind(R.id.sr_tour_refresh)
    SwipeRefreshLayout sRefresh;
    @Bind(R.id.lv_tour)
    ListView lvContent;
    ArrayList<DateBean.RowsBean> mListDate;
    private MyAdapter adapter;
    private int model;
    private int networkType;

    public TourBase(Activity mActivity) {
        super(mActivity);
    }

    @Override
    public void intiDate() {
        View view = View.inflate(mActivity, R.layout.base_tour, null);
        ButterKnife.bind(this, view);
        flContent.addView(view);
    }

    @Override
    public void intiDateForService() {
        sRefresh.setVisibility(View.INVISIBLE);
        llLoading.setVisibility(View.VISIBLE);
        //判断是否有缓存
        String cache = PrefUtils.getString("tour", "", mActivity);
        if (!cache.isEmpty()) {
            analysisDate(cache);
        }
        getDateForService();
        /**
         * 刷新数据
         */
        sRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDateForService();
                sRefresh.setRefreshing(false);
            }
        });
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //避免用户点击底部发生角标越界
                if (position < mListDate.size()) {
                    DateBean.RowsBean item = adapter.getItem(position);
                    Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                    intent.putExtra("title", item.getCHANNELNAME());
                    intent.putExtra("code", item.getID());
                    intent.putExtra("head", item.getTITLE());
                    intent.putExtra("cid", Constants.ID_TOUR_STATE);
                    mActivity.startActivity(intent);
                }
            }
        });
        lvContent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Vibrator vibrator = (Vibrator) mActivity.getSystemService(mActivity.VIBRATOR_SERVICE);
                vibrator.vibrate(60);

                if (position < mListDate.size()) {
                    DateBean.RowsBean item = adapter.getItem(position);
                    WebViewDialog.showDialog(mActivity, item.getID(), item.getTITLE(), Constants.ID_TOUR_STATE);
                }
                return true;
            }
        });
    }

    public void getDateForService() {
        getType();
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.GET, Constants.URL_TOUR_STATE_DATES, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                analysisDate(responseInfo.result);
                Log.i("branchDate", responseInfo.result);
                PrefUtils.putString("tour", responseInfo.result, mActivity);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(mActivity, "网络异常!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 判断网络网络环境以及,阅读模式
     */
    public void getType() {
        model = PrefUtils.getInt("model", SettingsModelState.MODEL_TEXT_AND_IMAGE, mActivity);
        Log.i("model", model + "模式");
        networkType = NetworkStateUtils.network(mActivity);
        Log.i("model", networkType + "网络状态");
    }

    /**
     * 解析数据
     *
     * @param result
     */
    private void analysisDate(String result) {
        Gson gson = new Gson();
        DateBean date = gson.fromJson(result, DateBean.class);
        mListDate = (ArrayList<DateBean.RowsBean>) date.getRows();
        adapter = new MyAdapter();
        lvContent.setAdapter(adapter);
        sRefresh.setVisibility(View.VISIBLE);
        llLoading.setVisibility(View.GONE);
    }

    class MyAdapter extends BaseAdapter {
        BitmapUtils bitmapUtils;

        MyAdapter() {
            bitmapUtils = new BitmapUtils(mActivity);
        }

        @Override
        public int getCount() {
            return mListDate.size();
        }

        @Override
        public DateBean.RowsBean getItem(int position) {
            return mListDate.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mActivity, R.layout.item_date_content, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DateBean.RowsBean date = getItem(position);
            Log.i("tourImagePath,", date.getPATHANDURL());
            //判断服务器是否返回图片，没有就影藏图片控件
            if (!date.getPATHANDURL().isEmpty()) {
                //图文模式
                if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
                    holder.ivPhoto.setVisibility(View.VISIBLE);
                    bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                } else if (model == SettingsModelState.MODEL_TEXT) {
                    //文本模式
                    holder.ivPhoto.setVisibility(View.GONE);
                } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
                    //智能模式
                    if (networkType == ConnectivityManager.TYPE_WIFI) {
                        //wifi状态
                        holder.ivPhoto.setVisibility(View.VISIBLE);
                        bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                    } else {
                        holder.ivPhoto.setVisibility(View.GONE);
                    }
                }
            } else {
                holder.ivPhoto.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(date.getTITLE());
            holder.tvTime.setText(date.getTIME());
            holder.tvType.setText(date.getCHANNELNAME());
            return convertView;
        }
    }

    public class ViewHolder {
        @Bind(R.id.iv_news_photo)
        ImageView ivPhoto;
        @Bind(R.id.tv_news_title)
        TextView tvTitle;
        @Bind(R.id.tv_news_time)
        TextView tvTime;
        @Bind(R.id.tv_news_type)
        TextView tvType;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

}
